package tag.in.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import tag.in.Constants;
import android.util.Log;

public class HTTPRequests {
	private static final String CLASSTAG = HTTPRequests.class.getSimpleName();
	private HttpClient client;
	
	public HTTPRequests() {
		client = new DefaultHttpClient();
	}
	
	/*
	 * Make a GET Request
	 */
	public String HTTPGet(String URL) {
		try {
			URI uri = new URI(URL);
			
			HttpGet get = new HttpGet(uri);
			HttpResponse responseGet = client.execute(get);
			StatusLine status = responseGet.getStatusLine();
			
			if(status.getStatusCode()==200) {
				InputStream data = responseGet.getEntity().getContent();
				
				return generateString(data);
			}else
				return null;
		} catch (Exception e) {
			Log.v(Constants.LOGTAG, " " + HTTPRequests.CLASSTAG + " GET Request Exception: " + e.getMessage());
		}
		return null;
	}
	
	/*
	 * Params list is created like this:
	 * 	List<NameValuePair> params = new ArrayList<NameValuePair>();
	 * 	params.add(new BasicNameValuePair("user", "kris"));
	 * 	params.add(new BasicNameValuePair("pass", "xyz"));
	 * 
	 */
	public int HTTPPost(String URL, List<NameValuePair> params) {
		try {
			HttpPost post = new HttpPost(URL); 
			
			UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
			post.setEntity(ent);
			HttpResponse responsePOST = client.execute(post);
			StatusLine status = responsePOST.getStatusLine();
			
			return status.getStatusCode();
			/*
			if(status.getStatusCode()==200) {
				HttpEntity resEntity = responsePOST.getEntity();
				if (resEntity != null) {
					return EntityUtils.toString(resEntity);
				}
			}else
				return null;
			*/
		} catch (Exception e) {
			Log.v(Constants.LOGTAG, " " + HTTPRequests.CLASSTAG + " POST Request Exception: " + e.getMessage());
		}
		
		return 0;
	}
	
	/*
	 * Make a POST Request with data
	 * 
	 */
	public int HTTPPostMime(String URL, List<NameValuePair> params, File file) {
		try {
			String data = "";
	        for(NameValuePair param: params){
	        	data += param.getName()+"="+param.getValue()+"&";
	        }
	        
			HttpPost httppost = new HttpPost(URL);

	        FileBody bin = new FileBody(file);
	        StringBody comment = new StringBody(data);

	        MultipartEntity reqEntity = new MultipartEntity();
	        reqEntity.addPart("info", comment);
	        reqEntity.addPart("bin", bin);
	        
	        httppost.setEntity(reqEntity);
	        
	        System.out.println("executing request " + httppost.getRequestLine());
	        HttpResponse response = client.execute(httppost);
	        StatusLine status = response.getStatusLine();
	        
	        Log.v("StatusCode",""+status.getStatusCode()+","+status.getReasonPhrase());
			
	        return status.getStatusCode();
	        
		} catch (Exception e) {
			Log.v(Constants.LOGTAG, " " + HTTPRequests.CLASSTAG + " POSTMime Request Exception: " + e.getMessage());
		}
		
		return 0;
	}
	
	public String generateString(InputStream stream) {
		InputStreamReader reader = new InputStreamReader(stream);
		BufferedReader buffer = new BufferedReader(reader);
		StringBuilder sb = new StringBuilder();
		try {
			String cur;
			while ((cur = buffer.readLine()) != null) {
				sb.append(cur + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			stream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return sb.toString();
	}
}
